package org.lyh.org.controller;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.lyh.base.util.Result;
import org.lyh.org.domain.Employee;
import org.lyh.org.query.EmployeeQuery;
import org.lyh.org.service.IEmployeeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/employee")
@Api(tags = "员工管理")
public class EmployeeController {
    @Autowired
    private IEmployeeService employeeService;

    @GetMapping
    @ApiOperation("查询所有员工")
    Result getEmpList() {
        try {
            return Result.success(employeeService.queryList());
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("后台未知错误！");
        }

    }

    @GetMapping("/{id}")
    @ApiOperation("根据ID查询员工")
    Result getEmpOne(@PathVariable("id") Long id) {
        Employee employee = employeeService.queryOne(id);
        return employee == null ? Result.error("查询的员工不存在！") : Result.success(employee);
    }

    @PutMapping
    @ApiOperation("更新或者新增员工")
    Result updateOrInsertEmp(@RequestBody Employee employee) {
        if (employee.getId()==null){
            employeeService.addOne(employee);
        }else {
            employeeService.updateOne(employee);
        }
        return Result.success();
    }
    @DeleteMapping("/{id}")
    @ApiOperation("根据ID删除员工")
    Result deleteEmp(@PathVariable("id") Long id) {
        try {
            employeeService.deleteById(id);
            return Result.success();
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("员工新增失败！");
        }

    }

    @ApiOperation("根据ids批量删除员工")
    @PatchMapping
    Result batchDelete(@RequestBody List<Long> ids) {
        try {
            employeeService.batchDelete(ids);
            return Result.success();
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("批量删除出错！");
        }
    }

    //高级查询及分页查询
    @ApiOperation("高级查询及分页查询")
    @PostMapping("/query")
    Result query(@RequestBody EmployeeQuery dto) {
        try {
            return Result.success(employeeService.queryPage(dto));
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("查询出错！");
        }
    }
}
